package com.business.web.spring;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

import com.auth.domain.T_user;
import com.business.domain.T_demo;
import com.business.domain.T_file_upload;
import com.business.service.T_file_uploadService;
import com.business.service.T_newsService;
import com.common.db.JsonVO;
import com.common.db.Pg;
import com.common.utils.BeanUtils;
import com.common.utils.DateUtil;
import com.common.utils.SystemConstants;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.log4j.Logger;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;
import org.json.simple.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

//@Service
//@Transactional
@Controller
@RequestMapping("/file")

public class FileuploadController {

    protected Logger log = Logger.getLogger(com.business.web.spring.FileuploadController.class);
    private Pg pg;

    @Value(value = "${upload.file.roopath}")
    private String savePath; //D:\\ideaSource\\tajg\\src\\main\\resources\\static\\attached

    @Value(value = "${upload.file.url}")
    private String saveUrl; //http://localhost:8080/attached/

    @Resource
    private T_file_uploadService t_file_uploadService;

    /**
     * 提供单个文件上传使用
     *
     * @param request
     * @param response
     * @throws Exception
     * @date 2021-5-12
     * @auth davexin
     */
    @PostMapping(value = "/uploadFileDB")
    @ResponseBody
    public JsonVO uploadFileDB(HttpServletRequest request, HttpServletResponse response, @RequestParam("file1") MultipartFile file1) {
        JsonVO vo = new JsonVO();
        vo.setResult("error");
        vo.setJieguo(false);
        T_file_upload t_file_upload = new T_file_upload();
        try {
            //*************************上传相关开始********************************************
            //判断file1不能为空;
            //String file1 = request.getParameter("file1");
            //request.
            if (file1 != null) {
                log.error("------本次上传文件名字=" + file1.getOriginalFilename());
                //保存文件
                //源文件名
                String oldFileName = file1.getOriginalFilename();
                //file类型
                String fileNameSuf = oldFileName.substring(oldFileName.lastIndexOf(".")).toLowerCase();
                //新的文件名：yyyyMMddHHmmss 格式；,把循环位置加上，防止程序执行过快，出现同名的文件名。
                String newFileName = request.getSession().getAttribute("userid")+"_"+ DateUtil.getCurrDateTime() + fileNameSuf;
                // 文件保存路径
                //String filePath = request.getSession().getServletContext().getRealPath("/") + "upload/";
                log.error("------file=" + savePath + ";oldFileName=" + oldFileName + ";newFileName=" + newFileName);
                //如果文件名称中涵：.exe;.bat等可执行文件，提示失败；
                String allowFileType = "pdf,txt,doc,docx,xls,xlsx,ppt,txt,zip,rar,gz,bz2,gif,jpg,jpeg,png,bmp,swf,flv,mp3,mp4,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb";

                //判断文件后缀是否允许；
                if (!allowFileType.contains(fileNameSuf.substring(1))) {
                    log.error("------后缀为：" + fileNameSuf + "的文件类型不能上传！");
                    vo.setInfo("后缀为：" + fileNameSuf + "的文件类型不能上传！");
                    return vo;
                }

                //如果文件大于5000M,不保存该文件,返回失败；
                if (file1.getSize() > 1024 * 1024 * 5000) {
                    vo.setInfo("文件：" + savePath + " 大于5000M,不保存，请上传小于5000M的文件！");
                    log.error("------文件：" + savePath + " 大于5000M,不保存，请上传小于5000M的文件！");
                    return vo;
                } else {
                    // 转存文件
                    file1.transferTo(new File(savePath + newFileName));
                    //保存到数据库；
                    t_file_upload.setFilegroup(request.getParameter("filegroup"));
                    t_file_upload.setFilename(newFileName);
                    t_file_upload.setExt1(oldFileName);
                    t_file_upload.setFilepath(savePath);
                    int retval = t_file_uploadService.save(t_file_upload);

                    vo.setResult("success");
                    vo.setJieguo(true);
                    vo.setInfo(oldFileName + "|" + newFileName+ "|" +retval);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            vo.setInfo(e.getMessage());
        }
        return vo;
    }

    /**
     * 删除上传附件组
     * @param  filegroup
     * @param request
     * @return Pg，json格式
     */
    @RequestMapping("/delUploadfileByGroupno")
    @ResponseBody
    public int delUploadfileByGroupno(String filegroup, HttpServletRequest request){
        T_file_upload t_file_upload = new T_file_upload();
        t_file_upload.setStartNo( 0 );
        t_file_upload.setPageSize( 1000 );
        t_file_upload.setEndNo( 1000 );

        t_file_upload.setFilegroup(filegroup);
        int retval = t_file_uploadService.deleteByFilegroup(t_file_upload);
        return  retval;
    }
    /**
     * 1、获取 T_demo信息列表，并且在列表页面展示
     * @param request
     * @return Pg，json格式
     */
    @RequestMapping("/getAllUploadfile")
    @ResponseBody
    public Pg getAllT_demo(HttpServletRequest request){
        int pageSize = 10;
        int startIndex = 0;
        T_file_upload t_file_upload = new T_file_upload();
        try{
            if(request.getParameter("pageSize")!=null){
                pageSize = BeanUtils.stringToInt("pageSizeFlag", request.getParameter("pageSize"));
            }
            if(request.getParameter("startIndex")!=null){
                startIndex = BeanUtils.stringToInt("startIndexFlag", request.getParameter("startIndex"));
            }

            if(request.getParameter("filegroup")!=null&&!"".equals(request.getParameter("filegroup"))){
                t_file_upload.setFilegroup(request.getParameter("filegroup"));
            }
            if(request.getParameter("filename")!=null&&!"".equals(request.getParameter("filename"))){
                t_file_upload.setFilename(request.getParameter("filename"));
            }

            if(request.getParameter("startdate")!=null&&!"".equals(request.getParameter("startdate"))){
                t_file_upload.setStartdate(request.getParameter("startdate"));
            }
            if(request.getParameter("enddate")!=null&&!"".equals(request.getParameter("enddate"))){
                t_file_upload.setEnddate(request.getParameter("enddate"));
            }
            t_file_upload.setStartNo( startIndex );
            t_file_upload.setPageSize( pageSize );
            t_file_upload.setEndNo( pageSize );
            List<T_demo> findAll = t_file_uploadService.findAll(t_file_upload);
            int totalCount = t_file_uploadService.findCountAll(t_file_upload);
            pg = new Pg(findAll, totalCount, pageSize, startIndex);
            request.setAttribute("t_demoList", findAll);
            request.setAttribute("pg", pg);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("------query getAllUploadfile error:"+e);
        }
        return pg;
    }

}
